/*
* 人事薪资发送管理页
*
* */
var layer;
var table;
var basePath;
var vm;
var tableColum;
var templateCode;

window.layinit(function (htConfig) {
    var _htConfig = htConfig;
    basePath = _htConfig.coreBasePath;
    uiBasePath = _htConfig.uiBasePath;
    vm = new Vue({
        el: '#app',
        data: {
            sendSalary: false,
            endDateModel: false,
            reCallModel : false,
            editSalary: false,
            loading: false,
            exporting: false,//导出标志位
            searchForm: {
                paydayTimeYear: '',  //发薪时间
                templateCode: '',  //工资表名
                keyworld: ''  //关键字

            },
            deleteForm: {
                tableName: '',
                params: []
            },
            eidtForm: {
                value: '',
                fieldName: '',
                jobCode: '',
                fileId: ''
            },
            timeForm:{
                endTime:'',
                endTimeV:'',
            },
            salaryTableNameList: [],  // 工资表名列表
            tableName: '',
            sendForm: {
                sendType: '',
                sendServer: [],
                endCheckTime: '',
                batchCode: '',
                sendBaseList: []
            },

            batchCode: '',
            templateCode: '',
            emailForm: {
                sendType: '',
                sendServer: ["1","2"],
                emailType: '1',
                endDate: '',
                batchCode: '',
                flag: '',
                isFailRetry:'',
                sendBaseList: []
            },
            reCallForm:{
                sendType: '',
                sendServer: ["1","2"],
            },
            emailFormValidate: {
                endTime: [
                    {required: true, message: '请选择时间'}
                ]

            },
            sendBaseDto: {
                email: '',
                jobCode: '',
                name: ''
            },

            selectRowData: [],
            currentData: [],

        },

        methods: {
            //重载表格
            toLoading: function () {
                if (table == null) {
                    return;
                }
                var self = this;
                self.loading = true;
                self.batchCode ='';
                self.getTableColum(self.searchForm.templateCode);
                if (tableColum !== null && tableColum !== '' && tableColum !== undefined) {
                    this.init();
                }
                self.countNumber();
            },
            handleReset: function (name) { // 重置表单
                var self = this;
                self.searchForm.paydayTimeYear = '';
                self.searchForm.templateCode = '';

                self.searchForm.keyworld = '';
                //var a=$("#trailerStartDate");
                //console.log(a);
                //alert(JSON.stringify(a));
                vm.toLoading();
            },
            ////  ----   单行操作界面显示  结束 -----------------
            clickExport: function () {//导出Excel表格
                var self = this;
                if (!self.batchCode) {
                    self.$Message.error('没有数据！');
                    return false;
                }
                if (!self.templateCode) {
                    self.$Message.error('导出模板为空！');
                    return false;
                }
                var jobCodes = '';
                if (self.selectRowData.length != 0) {
                    for (var i = 0; i < self.selectRowData.length; i++) {
                        if (jobCodes === '') {
                            jobCodes += self.selectRowData[i];
                        } else {
                            jobCodes += ',' + self.selectRowData[i];
                        }
                    }
                }

                var url = basePath + 'salaryExcel/downloadSalaryFile?templateCode=' + self.templateCode + '&batchCode='
                    + self.batchCode + '&keyworld=' + self.searchForm.keyworld;

                if (jobCodes !== '') {
                    url += '&jobCodes=' + jobCodes;
                }
                window.open(url);
            },
            init: function () {
                var self = this;
                //使用layerUI的表格组件
                layui.use(['layer', 'table', 'ht_ajax', 'ht_auth', 'ht_config'], function () {
                    layer = layui.layer;
                    table = layui.table;
                    //执行渲染
                    table.render({
                        elem: '#listTable' //指定原始表格元素选择器（推荐id选择器）
                        , id: 'listTable'

                        , cols: [tableColum], //设置表头
                        url: basePath + 'salarySheet/getSalaryTableData',
                        where: {

                            paydayTimeYear: self.searchForm.paydayTimeYear,  //发薪年份
                            templateCode: self.searchForm.templateCode, //发薪表名
                            keyworld: self.searchForm.keyworld  //关键字
                        },
                        page: true,
                        done: function (res, curr, count) {
                            //数据渲染完的回调。你可以借此做一些其它的操作
                            //如果是异步请求数据方式，res即为你接口返回的信息。
                            //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                            console.log("=-=================>>>>>>>>>>>表格结果", res.data);
                            var templateCode = self.searchForm.templateCode;
                            console.log("============templateCode:",templateCode);
                            self.templateCode = templateCode;
                            if(templateCode == 'MB2018042703'){
                                $("#sendAll").hide();
                                $("#withdrawAll").hide();
                                $("#setEndDate").hide();
                            }else {
                                $("#sendAll").show();
                                $("#withdrawAll").show();
                                $("#setEndDate").show();
                            }


                            self.currentData = res.data;

                            self.loading = false;
                            self.batchCode ='';
                            if (res.data !=null && res.data.length > 0) {
                                self.batchCode = res.data[0].batch_code;
                                if (res.data[0].finalState == 1) {
                                    $("#deleteAll").hide();
                                } else {
                                    $("#deleteAll").show();
                                }
                                self.countNumber();
                            }

                            var dom = $('#' + this.id).next();

                            dom.find('[lay-event="salaryPreview"]').optionsPopover({
                                title: "预览选择",
                                //disableHeader:false,
                                id: 'salaryPreview',
                                tableid: 'listTable',
                                width: 150,
                                contents: [

                                    {
                                        "name": "预览考勤", click: function (e, currentItem) {
                                            console.log("=============eee", e);
                                            console.log("=============currentItem", currentItem);
                                            var jobCode = currentItem.job_code;
                                            var batchCode = currentItem.batch_code;
                                            var sendType = 1;
                                            self.workTimePreview(jobCode, batchCode, sendType);
                                        }
                                    },
                                    {
                                        "name": "预览确认薪资", click: function (e, currentItem) {
                                            var jobCode = currentItem.job_code;
                                            var batchCode = currentItem.batch_code;
                                            var sendType = 2;
                                            var emailType = 1;
                                            self.salaryPreview(jobCode, batchCode, sendType,emailType);
                                        }
                                    },
                                    {
                                        "name": "预览发放薪资", click: function (e, currentItem) {
                                            var jobCode = currentItem.job_code;
                                            var batchCode = currentItem.batch_code;
                                            var sendType = 2;
                                            var emailType = 2;
                                            self.salaryPreview(jobCode, batchCode, sendType,emailType);
                                        }
                                    }
                                ]
                            });

                            dom.find('[lay-event="withdraw"]').optionsPopover({
                                title: "撤回选择",
                                width: 150,
                                //disableHeader:false,
                                id: 'withdraw',
                                tableid: 'listTable',
                                contents: [

                                    {
                                        "name": "撤回考勤邮件", click: function (e, currentItem) {
                                        console.log("========>>>初始化的templateCode", self.templateCode);
                                        var jobCode = currentItem.job_code;
                                        var batchCode = currentItem.batch_code;
                                        var sendType = 1;
                                        self.cancelEmail(2, jobCode, batchCode, sendType);
                                    }
                                    },
                                    {
                                        "name": "撤回薪资邮件", click: function (e, currentItem) {
                                        var jobCode = currentItem.job_code;
                                        var batchCode = currentItem.batch_code;
                                        var sendType = 2;
                                        self.cancelEmail(2, jobCode, batchCode, sendType);
                                    }
                                    }
                                ]
                            });


                        }
                    });
                    table.on('edit(listTable)', function (obj) {
                        console.log("=======>>>>>>>单元格修改属性", obj);
                        self.updataSalary(obj);
                    });
                    table.on('tool(listTable)', function (obj) {
                        var selectedRowInfo = obj.data;
                        if (obj.event === 'delete') {
                            layer.confirm('真的删除么?', function (index) {
                                self.deleteForm.params.push(obj.data);
                                self.deleteSalaryData();
                                layer.close(index);
                            });
                        }

                        if (obj.event === 'resend') {
                            //重发
                            if (self.templateCode === 'MB2018042701') {
                                //考勤
                                self.emailForm.sendType = '1';
                            }
                            if (self.templateCode === 'MB2018042702') {
                                //工资
                                self.emailForm.sendType = '2';
                            }
                            self.sendSalary = true;
                            self.emailForm.flag = '2';
                            self.sendBaseDto.jobCode = selectedRowInfo.job_code;
                            self.emailForm.sendBaseList.push(self.sendBaseDto);
                        }

                    });


                    table.on('checkbox(listTable)', function (obj) {
//                    	  console.log(self.currentData);
//                    	  console.log(obj.checked); //当前是否选中状态
//                    	  console.log(obj.data); //选中行的相关数据
//                    	  console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
                        if (obj.type === 'all') {
                            if (obj.checked) {
                                self.selectRowData = [];
                                if (self.currentData.length != 0) {
                                    for (var i = 0; i < self.currentData.length; i++) {
                                        self.selectRowData.push(self.currentData[i].job_code);
                                    }
                                    ;
                                }
                            } else {
                                self.selectRowData = [];
                            }
                        } else {
                            if (obj.checked) {
                                self.selectRowData.push(obj.data.job_code);
                            } else {
                                var idx = self.findJobCode(self.selectRowData, obj.data.job_code);
                                if (idx !== -1) {
                                    self.selectRowData.splice(idx, 1);
                                }
                            }
                        }

                    });
                })
            },

            // 查找元素
            findJobCode: function (datas, jobCode) {
                for (var i = 0; i < datas.length; i++) {
                    if (datas[i] == jobCode) {
                        return i;
                    }
                }
                return -1;
            },
            cancelEmail: function (type, jobCode, batchCode, sendType,sendServer) {
                var self = this;
                console.log("sendserver=",sendServer);
                var url = basePath + "sendinfo/sendRecall?sendType=" + sendType + "&jobCode=" + jobCode + "&batchCode=" + batchCode + "&type=" + type+ "&sendServer=" + sendServer;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========", result);
                        if (result.returnCode == "0") {
                            layer.msg("撤回成功");
                            self.toLoading();
                        } else {
                            layer.msg("撤回失败：" + result.msg);
                        }
                    },
                    error: function (result) {
                        layer.msg("撤回失败：" + result.msg);
                    }

                });
            },
            getTableColum: function (templateCode) {
                var self = this;
                self.deleteForm.templateCode = templateCode;
                var batchCode = self.batchCode;
                var url = basePath + "salarySheet/getTableColum?templateCode=" + templateCode + "&queryType=2&batchCode=" + batchCode;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========", result);
                        if (result.returnCode == "0") {
                            console.log("动态表名==========", result.data);
                            tableColum = result.data.data;
                            self.templateCode = result.data.templateCode;
                            console.log("返回参数=====", tableColum);
                            var type = result.data.type;
                            if (type === '0') {
                                self.searchForm.paydayTimeYear = result.data.time;
                                self.countNumber.paydayTimeYear = result.data.time;
                                self.searchForm.templateCode = result.data.templateCode;
                                self.countNumber.templateCode = result.data.templateCode;
                            }

                        }
                    }

                });
            },
            //删除
            deleteSalaryData: function () {
                var self = this;
                var url = basePath + "salarySheet/deleteSalaryData";

                var data = JSON.stringify(self.deleteForm);
                console.log("data========>>>>>>", data);
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    data: data,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========", result);
                        if (result.returnCode == "0") {
                            self.toLoading();
                        } else {
                            vm.$Message.error('接口调用异常!');
                        }

                    },
                    error: function (result) {
                        vm.$Message.error('接口调用异常!');
                    }

                });
            },
            //工资条预览
            salaryPreview: function (jobCode, batchCode, sendType,emailType) {
                var url = "/salarySend/salaryEmailCheckInner?sendType=" + sendType + "&jobCode=" + jobCode + "&batchCode=" + batchCode+"&emailType="+emailType;
                var tile = "预览";
                var openIndex = layer.open({
                    type: 2,
                    area: ['80%', '80%'],
                    fixed: false,
                    maxmin: true,
                    title: tile,
                    content: url
                });

            },
            workTimePreview: function (jobCode, batchCode, sendType) {
                var url = "/salarySend/workTimeCheckInner?sendType=" + sendType + "&jobCode=" + jobCode + "&batchCode=" + batchCode;
                var tile = "预览";
                var openIndex = layer.open({
                    type: 2,
                    area: ['80%', '80%'],
                    fixed: false,
                    maxmin: true,
                    title: tile,
                    content: url
                });

            },
            endDateSet: function () {
                var self = this;

                var validateFlag = false;
                self.$refs["timeForm"].validate(function (valid) {
                    if (valid) {
                        validateFlag = true;
                        // self.sendSalary = false;
                    }
                });
                if (!validateFlag) {
                    return;
                }
                var time= vm.timeForm.endTime;
                var d = new Date(time);
                var  resTime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() ;

                var batchCode=vm.batchCode;
                var url = basePath + "sendinfo/setEndTime?endTime=" + resTime + "&batchCode=" + batchCode;

                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        if (result.returnCode == "0") {
                            layer.msg("设置成功");
                            self.endDateModel = false;
                        } else {
                            layer.msg(result.msg);
                        }
                    },
                    error: function (result) {
                        layer.msg("发送失败：" + result.msg);
                        self.toLoading();
                    }

                });



            },

            cancelEndDate:function () {
                var self = this;
                self.endDateModel = false;
            },
            confirmSend: function () {
                var self = this;
                self.emailForm.batchCode = self.batchCode;

                var validateFlag = false;
                self.$refs["emailForm"].validate(function (valid) {
                    if (valid) {
                        validateFlag = true;
                        self.sendSalary = false;
                    }
                });
                if (!validateFlag) {
                    return;
                }
                var url = basePath + "sendinfo/sendSalaryEmail";

                var data = JSON.stringify(self.emailForm);
                console.log("data========>>>>>>", data);
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    data: data,
                    dataType: "json",
                    success: function (result) {
                        self.emailForm.isFailRetry = '0';
                        if (result.returnCode == "0") {
                            layer.msg("发送成功");
                            self.toLoading();
                        } else {
                            layer.msg(result.msg);
                            self.toLoading();
                        }
                    },
                    error: function (result) {
                        self.emailForm.isFailRetry = '0';
                        layer.msg("发送失败：" + result.msg);
                        self.toLoading();
                    }

                });

            },
            cancelSend: function () {
                var self = this;
                self.sendSalary = false;
                self.emailForm.isFailRetry = '0';

            },
            setEndDate: function () {
                var self = this;
                self.endDateModel = true;
            },
            //全部发送
            sendAll: function () {
                var self = this;
                self.sendSalary = true;
                self.emailForm.flag = '1';
                self.emailForm.sendBaseList = null;
                if (self.templateCode == 'MB2018042701') {
                    //考勤
                    self.emailForm.sendType = 1
                    $("#xzRadio").hide();
                    $("#kqRadio").show();
                    $("#emailType").hide();
                }
                if (self.templateCode == 'MB2018042702') {
                    //薪资
                    self.emailForm.sendType = 2
                    $("#kqRadio").hide();
                    $("#xzRadio").show();
                    $("#emailType").show();
                }

            },
            failRetry: function(){
                var self = this;
                self.sendSalary = true;
                self.emailForm.flag = '2';
                self.emailForm.sendBaseList = null;
                self.emailForm.isFailRetry = '1';
                if (self.templateCode == 'MB2018042701') {
                    //考勤
                    self.emailForm.sendType = 1
                    $("#xzRadio").hide();
                    $("#kqRadio").show();
                    $("#emailType").hide();
                }
                if (self.templateCode == 'MB2018042702') {
                    //薪资
                    self.emailForm.sendType = 2
                    $("#kqRadio").hide();
                    $("#xzRadio").show();
                    $("#emailType").show();
                }
            },
            //全部撤回
            withdrawAll: function () {
                var self = this;
                // self.cancelSend(1,self.batchCode);
                // layer.confirm('请选择撤回类型', {
                //     btn: ['考勤邮件', '薪资邮件'] //按钮
                // }, function () {
                //     self.cancelEmail(1, '', self.batchCode, 1);
                // }, function () {
                //     self.cancelEmail(1, '', self.batchCode, 2);
                // });
                self.reCallModel = true;
                self.reCallForm.flag = '1';
                self.reCallForm.sendBaseList = null;
                if (self.templateCode == 'MB2018042701') {
                    //考勤
                    self.reCallForm.sendType = 1
                    $("#xzRadio").hide();
                    $("#kqRadio").show();
                }
                if (self.templateCode == 'MB2018042702') {
                    //薪资
                    self.reCallForm.sendType = 2
                    $("#kqRadio").hide();
                    $("#xzRadio").show();
                }
            },
            reCallSend:function () {
                var self = this;
                var sendType=self.reCallForm.sendType;
                var sendServer=self.reCallForm.sendServer;
                self.cancelEmail(sendType, '', self.batchCode, sendType,sendServer);
                self.reCallModel=false;

            },
            cancelReCall:function () {
                var self = this;
                self.reCallModel = false;
            },
            //多条删除
            deleteAll: function () {
                var self = this;
                var checkStatus = table.checkStatus('listTable');
                if (checkStatus.data.length == 0) {
                    layer.open({
                        title: '警告'
                        , content: '请勾选数据'
                    });
                    return;
                }
                layer.confirm('真的删除么?', function (index) {
                    self.deleteForm.params = checkStatus.data;
                    self.deleteSalaryData();
                    layer.close(index);
                });

            },

            // 校验单元格姓名及邮箱类型
            updataSalary: function (obj) {
                var value = obj.value //得到修改后的值
                    , data = obj.data //得到所在行所有键值
                    , field = obj.field; //得到字段
                var self = this;
                self.eidtForm.value = value;
                self.eidtForm.fieldName = field;
                self.eidtForm.fileId = data.file_id;
                self.eidtForm.jobCode = data.job_code;
                self.eidtForm.batchCode = data.batch_code;
                var url = basePath + "salarySheet/validateUpdataSalary";

                var data = JSON.stringify(self.eidtForm);
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    data: data,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========", result);
                        if (result.returnCode == "0") {
                            self.updataSalaryExt(obj);
                        } else if (result.returnCode == "9996") {
                            layer.confirm(result.msg, {
                                btn: ['确认', '取消'] //可以无限个按钮
                            }, function (index, layero) {
                                self.updataSalaryExt(obj);
                            }, function (index) {
                                self.toLoading();
                            });
                        } else {
                            layer.msg(result.msg);
                            self.toLoading();
                        }
                    },
                    error: function (result) {
                        layer.msg("更新失败：" + result.msg);
                    }

                });
            },
            //单元格更新
            updataSalaryExt: function (obj) {
                var value = obj.value //得到修改后的值
                    , data = obj.data //得到所在行所有键值
                    , field = obj.field; //得到字段
                var self = this;
                self.eidtForm.value = value;
                self.eidtForm.fieldName = field;
                self.eidtForm.fileId = data.file_id;
                self.eidtForm.jobCode = data.job_code;

                var url = basePath + "salarySheet/updataSalary";

                var data = JSON.stringify(self.eidtForm);
                console.log("data========>>>>>>", data);
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    data: data,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========", result);
                        if (result.returnCode == "0") {
                            console.log("动态表名==========", result.data);
                            layer.msg("更新成功");
                            self.toLoading();
                        } else {
                            layer.msg(result.msg);
                            self.toLoading();
                        }
                    },
                    error: function (result) {
                        layer.msg("更新失败：" + result.msg);
                    }

                });

            },

            finalState: function () {
                var self = this;
                layer.confirm('入库后数据不可修改', function (index) {
                    self.updateFinalState(self.batchCode, self.templateCode)
                    layer.close(index);
                });
            },
            updateFinalState: function (batchCode, templateCode) {
                var self = this;
                var url = basePath + "salarySheet/updateFinalState?batchCode=" + batchCode + "&templateCode=" + templateCode;

                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        console.log("结果：========", result);
                        if (result.returnCode == "0") {
                            layer.msg("入库成功");
                            self.toLoading();
                        } else {
                            layer.msg(result.msg);
                            self.toLoading();
                        }
                    },
                    error: function (result) {
                        layer.msg("入库失败：" + result.msg);
                    }

                });
            },
            countNumber: function () {
                var self = this;
                // var tempcode = self.searchForm.templateCode;
                // var sendtime = self.searchForm.paydayTimeYear;
                var batchCode=self.batchCode;
                console.log("11111111111=",batchCode);

                var url = basePath + "sendinfo/countSendNumber?batchCode=" + batchCode ;
                $.ajax({
                    type: "GET",
                    url: url,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    success: function (result) {
                        if (result.returnCode == "0") {
                            var data = result.data;
                            $("#countNumber").html(data.countNumber);
                            $("#preSendNumber").html(data.preSendNumber);
                            $("#sendedNumber").html(data.sendedNumber);
                            $("#callNumber").html(data.callNumber);
                            $("#failNumber").html(data.failNumber);
                            $("#dpreSendNumber").html(data.dpreSendNumber);
                            $("#dsendedNumber").html(data.dsendedNumber);
                            $("#dcallNumber").html(data.dcallNumber);
                            $("#dfailNumber").html(data.dfailNumber);
                        }
                    },
                    error: function (result) {

                    }

                });

            }

        },
        mounted: function () {
            var self = this;
            self.getTableColum(self.searchForm.templateCode);

            if (tableColum !== null && tableColum !== '' && tableColum !== undefined) {
                this.init();
            }


        }

    });

});
//














